package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.zsmart.core.util.DateUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 资源核查全程要求完成时间
 */
@Service
public class WholeRequireFinishTimeAttrHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;

    @Override
    public void init(CommonAttrVO commonAttr) {

        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteProdInst prodInst = querySceneInstService.listProdInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteSceneInst.getRootInstId()).stream()
            .filter(inst -> !KiteStringUtils.equalsAny(inst.getActionType().name(), ActionType.X.name(), ActionType.D.name()))
            .findFirst().orElse(null);
        String defaultValue = DateFormatUtils.businessDaysMinute(new Date(), 3);
//        资源核查
        String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        if(sceneInst.getServiceOfferId().equals(LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK)){
            if("OrderResubmit".equals(nodeCode)){
                String value = compareDate(commonAttr,prodInst);
                commonAttr.setValue(value);
                commonAttr.setValueDesc(value);
                defaultValue = value;
            }else{
                String offerId = querySceneInstService.getOfferInst(kiteSceneInst.getCustId(), kiteSceneInst.getRootInstId()).getOfferId();

                defaultValue = LocalAttrUtils.getInstance().wholeOffsetDayOB(prodInst.getSpecId(), null, null, offerId);
                commonAttr.setValue(defaultValue);
                commonAttr.setValueDesc(defaultValue);
                commonAttr.setDefaultValue(defaultValue);
            }
            KiteAttr finishTime = querySceneInstService
                .getCommonAttrsByFieldName(sceneInstId, commonAttr.getFieldName(), "204");
            finishTime.setDefaultValue(defaultValue);
            finishTime.setValue(defaultValue);
            finishTime.setValueDesc(defaultValue);
            operateSceneCommonService.setCommonAttr(sceneInstId, finishTime);
            setCommonAttr(commonAttr);
            return;
        }
        //        核查追单追单校验
        String BIZ_TYPE = MapUtils.getString(this.querySceneInstService.getExtParameter(sceneInstId),"serviceOfferId");
        if (KiteStringUtils.equals(LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW, BIZ_TYPE)&&"OrderResourceCheck".equals(nodeCode)) {
            String value = compareDate(commonAttr,prodInst);
            commonAttr.setValue(value);
            commonAttr.setValueDesc(value);
            KiteAttr finishTime = querySceneInstService
                .getCommonAttrsByFieldName(sceneInstId, commonAttr.getFieldName(), "204");
            finishTime.setDefaultValue(value);
            operateSceneCommonService.setCommonAttr(sceneInstId, finishTime);
            setCommonAttr(commonAttr);
            return;
        }
        commonAttr.setValue(defaultValue);
        commonAttr.setValueDesc(defaultValue);
        setCommonAttr(commonAttr);
}

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        defaultCheck(sceneInstId,fieldName,value);
        if (KiteStringUtils.isEmpty(value)){
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        // 是否为页面初始化渲染，是（T），跳过校验
        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
        if (KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
            return super.apply(sceneInstId, fieldName, value, value);
        }
        String allCompleteTimePattern = "yyyy-MM-dd HH:mm:ss";
        String azCompleteTimePattern = "yyyy-MM-dd HH:mm:ss";
        Date curDate = getCurrentDate();
        Date allCompleteTime = null;
        if (KiteStringUtils.isNotEmpty(value)) {
            String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
            if (allCompleteTimePattern.length() > value.length()) {
                allCompleteTimePattern = allCompleteTimePattern.substring(0, value.length());
            }
            try {
                allCompleteTime = DateUtils.parseStrToDate(value, allCompleteTimePattern);
            } catch (Exception e) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
            }
            //全程要求完成时间不能早于当前时间
            if (DateUtil.compare(curDate, allCompleteTime) > 1) {
                BssException.throwOut("", "", "要求完成时间不能早于当前时间");
            }

            String scenInstId = KiteWebContext.getContext().getCurrentSceneInstId();
            List<KiteProdInst> prodInstList = querySceneInstService.listProdInsts(scenInstId);
            //A端要求完成时间
            String aCompleteTimeStr = querySceneInstService.getCommonAttrValue(sceneInstId, "2_0000122");
            //Z端要求完成时间
            String zCompleteTimeStr = querySceneInstService.getCommonAttrValue(sceneInstId, "2_0000123");
            List<String> list = new ArrayList<>();
            list.add(aCompleteTimeStr);
            list.add(zCompleteTimeStr);
            for (String complteTimeStr : list) {
                if (KiteStringUtils.isNotEmpty(complteTimeStr)) {
                    if (azCompleteTimePattern.length() > complteTimeStr.length()) {
                        azCompleteTimePattern = azCompleteTimePattern.substring(0, complteTimeStr.length());
                    }

                    Date completeDate = null;
                    try {
                        completeDate = DateUtils.parseStrToDate(complteTimeStr, azCompleteTimePattern);
                    } catch (Exception e) {
                        ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
                    }

                    //AZ端完成时间需要小于全局完成当前时间
                    if (null != completeDate && DateUtil.compare(completeDate, allCompleteTime) > 1) {

                        // 是否为页面初始化渲染，是（T），跳过校验
                        if (KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
                            return super.apply(sceneInstId, fieldName, value, value);
                        }
                        if (KiteStringUtils.equalsAny(nodeCode, "OrderSigned")) {
                            // 签订环节不做校验
                            return super.apply(sceneInstId, fieldName, value, value);
                        } else {
                            BssException.throwOut(KeyConsts.LOG_MODULE, "", "A、Z端要求完成时间不能晚于全程要求完成时间");
                        }
                    }
                }
            }
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    public String compareDate(CommonAttrVO commonAttr,KiteProdInst prodInst){
        String nowFinishTime = LocalAttrUtils.getInstance().wholeOffsetDay(prodInst.getProdId(), null);
        String origin = commonAttr.getOriginValue();
        if(null==origin){
            origin=commonAttr.getOldValue();
        }
        if(origin==null){
            return nowFinishTime;
        }
        if(DateFormatUtils.compareDate(origin, nowFinishTime, DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
            return nowFinishTime;
        }else{
            return origin;
        }
    }
    public void defaultCheck(String sceneInstId ,String fieldName,String value){
        // 是否为页面初始化渲染，是（T），跳过校验

        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
        if(null!=isInitPageRenderFlag&&KiteStringUtils.isEqual(isInitPageRenderFlag, LocalKeyConsts.IFTRUE_T)) {
            KiteAttr finishTime = querySceneInstService.getCommonAttrsByFieldName(sceneInstId, fieldName, "204");
            if(finishTime!=null&&KiteStringUtils.isNotEmpty(finishTime.getDefaultValue())&&DateFormatUtils.compareDate(value,finishTime.getDefaultValue() , DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("可选择的日期不能早于初始化的日期:"+finishTime.getDefaultValue());
            }
        }
    }
    public void checkTime(String type, KiteAttr ...attr) {
        if (Objects.isNull(attr)) {
            return;
        }
        List<KiteAttr> kiteAttrList = Arrays.asList(attr);
        if (KiteListUtils.isNotEmpty(kiteAttrList)) {
            kiteAttrList.forEach(kiteAttr -> {
                String currDate = kiteAttr.getValue();
                String originDate = kiteAttr.getOriginValue();
                // 如果加急，不能晚于之前的完成时间
                if ("URGENT".equals(type) && KiteStringUtils.isNotEmpty(originDate)) {
                    if (DateFormatUtils.compareDate(currDate, originDate, LocalKeyConsts.DATE_FORMAT) > 0) {
                        BssException.throwOut(KeyConsts.LOG_MODULE, "","加急，要求完成时间不能晚于之前的完成时间");
                    }
                }
                // 如果是延期，不能早于之前的完成时间
                if ("POSTPONE".equals(type) && KiteStringUtils.isNotEmpty(originDate)) {
                    if (DateFormatUtils.compareDate(currDate, originDate, LocalKeyConsts.DATE_FORMAT) < 0) {
                        BssException.throwOut(KeyConsts.LOG_MODULE, "","延期，要求完成时间不能早于之前的完成时间");
                    }
                }
                // 校验全程要求完成时间大于当前时间
                if ("ORD10012".equals(kiteAttr.getFieldName()) && (DateFormatUtils.compareDate(currDate, DateFormatUtils.getFormatedDate(), LocalKeyConsts.DATE_FORMAT) < 0)) {
                    BssException.throwOut(KeyConsts.LOG_MODULE, "","全程要求完成时间不能小于当前时间");
                }
            });
        }
    }
    public Date getCurrentDate() {
        Date toDay = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String toDayStr = sdf.format(toDay);
        Date newDate = null;
        try {
            newDate = sdf.parse(toDayStr);

        } catch (Exception e) {
            return newDate;
        }
        return newDate;
    }
}
